<template>
<div>
  <loading v-if="!detail"/>
  <div class="contract" v-if="detail">
    <div class="header">
      <div class="pic">
        <img :src="detail.imageUrl" alt="">
      </div>
      <div class="info">
        <p class="title ellipsis">{{detail.name}}</p>
        <p class="rule">{{detail.signNum || 0}}次 | {{detail.dayKm || 0}}公里 | {{detail.cost || 0}}元/次</p>
        <p class="creater">由{{detail.nickName || detail.creatorId}}发起  <router-link to="/contract/ruler">规则说明 ></router-link></p>
      </div>
    </div>
    <div class="time">
      <div class="sign-time">
        <p>打卡时间（{{detail.startTime | formatTime}} - {{detail.endTime | formatTime}}）</p>
        <span>{{status}}</span>
      </div>
      <div class="time-box vux-1px-b">
        <div class="item" v-for="item in getBetweenDateStr" :key="item">
          <i class="iconfont" v-if="detail.signDays.includes(item/1000)">&#xe62b;</i>
          <p :class="{'active':detail.signDays.includes(item/1000)}">{{new Date(item).getDate()}}</p>
        </div>
      </div>
    </div>
    <div class="data-info vux-1px-b">
      <div class="money">
        <b>{{detail.totalCost || 0}}</b>
        <span>约定金额(元)</span>
      </div>
      <div class="bonus">
        <b>{{detail.win || 0}}</b>
        <span>获得奖金</span>
      </div>
      <div class="members">
        <b>{{detail.actualJoin}}</b>
        <span>参与人数</span>
      </div>
    </div>
    <div class="action">
      <button type="button" :class="{'before':  btnStatus[0] === 1,'runing': btnStatus[0] === 4, 'stop': btnStatus[0] === 6}" @click="runAction" :disabled="disBtn">{{btnStatus[1]}}</button>
      <p class="linkto" @click="linkto">赞助跑班</p>
    </div>
    <div class="support">
      <div class="item" v-for="(item, index) in detail.sponsor" :key="index">
        <span class="supporter">
          <img :src="item.imageUrl" alt="" v-if="item.imageUrl">
          <img src="@/assets/images/male.png" alt="" v-if="!item.imageUrl&&item.sex===0">
          <img src="@/assets/images/female.png" alt="" v-if="!item.imageUrl&&item.sex===1">
          {{item.nickName}}赞助了奖金
        </span>
        <span class="money">￥{{item.amount || 0}}</span>
      </div>
    </div>
    <div class="instraction">
      <span>跑团介绍</span>
      <p class="">{{detail.introduce}}</p>
    </div>
    <div class="rank">
      <p class="title vux-1px-b">跑班排名</p>
      <div class="rank-box">
        <div class="item vux-1px-b" v-for="(item,index) in rank" :key="index">
          <div class="user">
            <img :src="item.imageUrl" v-if="item.imageUrl">
            <img src="@/assets/images/male.png" alt="" v-else>
            <p class="name">{{item.nickName}}</p>
            <p class="ranking" v-if="item.rank !== 0">第{{item.rank}}名</p>
            <p class="ranking" v-else>暂无排名</p>
          </div>
          <div class="progress">
            <p class="icon" :style="{ paddingLeft: item.totalSign/item.signNum*90 + '%' }">
              <img :src="item.imageUrl" alt="" v-if="item.imageUrl">
              <img src="@/assets/images/male.png" alt="" v-if="!item.imageUrl&&item.sex===0">
              <img src="@/assets/images/female.png" alt="" v-if="!item.imageUrl&&item.sex===1">
            </p>
            <div class="box">
              <div v-if="item.totalSign > 0" class="current" :style="{ width: item.totalSign/item.signNum*100 + '%' }"></div>
            </div>
          </div>
        </div>
        <div class="nodata" v-if="rank.length === 0">暂无排名</div>
        <div class="nomore" v-if="rank.length === total && rank.length > 0">没有更多了</div>
        <div infinite-wrapper>
          <infinite-loading @infinite="getList">
            <span slot="no-more"></span>
          </infinite-loading>
        </div>
      </div>
      
    </div>
  </div>
</div>
</template>

<script>
import api from '@/api/contract'
import InfiniteLoading from 'vue-infinite-loading'
import pingpp from 'pingpp-js'
import Loading from '@/components/loading'
import axios from 'axios'
export default {
  components: {
    InfiniteLoading,
    Loading
  },
  data () {
    return {
      activityId: '',
      detail: '',
      rank: [],
      pageIndex: 1,
      offset: 10,
      total: '',
      disBtn: false
    }
  },
  watch: {
    $route (to, from) {
      if (this.$route.query.token) {
        let token = this.$route.query.token
        window.localStorage.setItem('token', token)
        axios.defaults.headers.common['Authorization'] = token
        this.getData()
      }
    }
  },
  methods: {
    // 获取约定跑详情
    getDetail () {
      api.getDetail({activityId: this.activityId}).then((res) => {
        if (res.data.code === 200) {
          this.detail = res.data.data
        } else if (res.data.code === 313) {
          window.location.reload()
        } else {
          this.$vux.toast.text('获取约定跑详情失败！', 'center')
        }
      }).catch()
    },
    // 获取约定跑成员
    getList ($state) {
      if (this.total === this.rank.length) {
        $state.complete()
        return false
      }
      api.getList({
        activityId: this.activityId,
        pageIndex: this.pageIndex,
        offset: this.offset
      }).then((res) => {
        if (res.data.code === 200) {
          this.rank.push(...res.data.data.list)
          this.pageIndex += 1
          this.total = res.data.data.total
          $state.loaded()
        } else {
          $state.complete()
        }
      }).catch()
    },
    // 点击按钮报名
    runAction () {
      if (this.disBtn) {
        return false
      }
      this.disBtn = true
      // 加入约定跑
      if (this.btnStatus[0] === 2 || this.btnStatus[0] === 5) {
        if (this.detail.isJoin === 2) {
          this.$vux.toast.text('你已加入其它约定跑！', 'center')
          return false
        }
        api.join({
          activityId: this.activityId,
          channel: 'wx_pub'
        }).then((res) => {
          this.disBtn = false
          if (res.data.code === 200) {
            this.pingppAction(res.data.data.charge)
          } else {
            this.$vux.toast.text('加入约定跑失败！', 'center')
          }
        }).catch(() => {
          this.disBtn = false
        })
      }
      // 开始跑步
      if (this.btnStatus[0] === 3) {
        this.download()
      }
    },
    // ping++支付
    pingppAction (object) {
      let _this = this
      pingpp.createPayment(object, function (result, err) {
      // object 需是 Charge/Order/Recharge 的 JSON 字符串
      // 可按需使用 alert 方法弹出 log
        // console.log(result)
        // console.log(err.msg)
        // console.log(err.extra)
        if (result === 'success') {
          // 只有微信公众号 (wx_pub)、微信小程序（wx_lite）、QQ 公众号 (qpay_pub)支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL
          _this.$vux.toast.text('加入约定跑成功！', 'center')
          window.location.reload()
        } else if (result === 'fail') {
          // Ping++ 对象 object 不正确或者微信公众号/微信小程序/QQ公众号支付失败时会在此处返回
          _this.$vux.toast.text('加入约定跑失败！', 'center')
        } else if (result === 'cancel') {
          // 微信公众号、微信小程序、QQ 公众号支付取消支付
          _this.$vux.toast.text('加入约定跑失败！', 'center')
        }
      })
    },
    // 赞助跑班
    linkto () {
      if (this.btnStatus[0] === 6) {
        this.$vux.toast.text('约定跑已结束，不能赞助跑班！', 'center')
        return false
      }
      this.$router.push({path: '/support', query: {activityId: this.activityId, userId: this.userId}})
    },
    // 下载app
    download () {
      let u = navigator.userAgent
      let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 // g
      let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
      let url = ''
      if (isAndroid) {
        url = 'http://sj.qq.com/myapp/detail.htm?apkName=com.odun.odunRunning'
      } else if (isIOS) {
        url = 'https://itunes.apple.com/cn/app/%E6%AC%A7%E7%9B%BE%E9%85%B7%E8%B7%91/id1279128697?mt=8'
      } else {
        url = 'http://sj.qq.com/myapp/detail.htm?apkName=com.odun.odunRunning'
      }
      window.location.href = url
    },
    // 授权后获取数据、参数
    getData () {
      this.activityId = this.$route.query.activityId || ''
      this.userId = this.$route.query.userId || ''
      this.getDetail()
    }
  },
  filters: {
    formatTime (val) {
      let date = new Date(val * 1000)
      let m = date.getMonth() + 1
      let d = date.getDate()
      return `${m}.${d}`
    }
  },
  computed: {
    // 活动状态
    status () {
      let data = new Date().getTime()
      let start = this.detail.startTime * 1000
      let end = this.detail.endTime * 1000
      let diffstart = Math.ceil((start - data) / 86400000)
      let diffend = Math.ceil((end - data) / 86400000)
      return data > start ? (data <= end ? `${diffend}天结束` : '已结束') : `${diffstart}天开始`
    },
    // 计算按钮状态
    btnStatus () {
      let date = new Date().getTime()
      let start = this.detail.startTime * 1000
      let end = this.detail.endTime * 1000
      let lastday = Math.floor((end - date) / (24 * 60 * 60 * 1000))
      let isJoin = this.detail.isJoin
      if (date < start) {
        return isJoin === 1 ? [1, '即将开始'] : [2, '加入约定跑']
      } else if (date > start && date < end) {
        return isJoin === 1 ? [3, '开始跑步'] : (lastday < this.detail.signNum ? [4, '进行中'] : [5, '插班报名'])
      } else {
        return [6, '已结束']
      }
    },
    // 计算活动时间之间的日期
    getBetweenDateStr () {
      let result = []
      let startTime = new Date(this.detail.startTime * 1000)
      let endTime = new Date(this.detail.endTime * 1000)
      while ((endTime.getTime() - startTime.getTime()) >= 0) {
        // var year = startTime.getFullYear()
        // var month = startTime.getMonth().toString().length === 1 ? '0' + startTime.getMonth().toString() : startTime.getMonth()
        // var day = startTime.getDate().toString().length === 1 ? '0' + startTime.getDate() : startTime.getDate()
        // result.push(`${year}-${month}-${day}`)
        result.push(startTime.getTime())
        startTime.setDate(startTime.getDate() + 1)
      }
      return result
    }
  },
  created () {
    if (!this.$route.query.token) {
      this.common.wechatlogin()
    } else {
      let token = this.$route.query.token
      window.localStorage.setItem('token', token)
      axios.defaults.headers.common['Authorization'] = token
      this.getData()
    }
  },
  mounted () {
  }
}
</script>

<style lang="scss" scoped>
.contract{
  padding: 1rem;
  overflow: hidden;
  .header{
    display: flex;
    .pic{
      width: 9rem;
      margin-right: 1rem;
      img{
        width: 9rem;
        height: 9rem;
        border-radius: 3px;
      }
    }
    .info{
      .title{
        font-size: 1.6rem;
        padding-top: 1rem;
      }
      .rule{
        font-size: 1.2rem;
        padding: 1rem 0;
      }
      .creater{
        font-size: 1.2rem;
        color: #666;
        a{
          color: #4A90E2;
          margin-left: 0.5rem;
        }
      }
    }
  }
  .time{
    padding-top: 1.5rem;
    .sign-time{
      display: flex;
      font-size: 1.4rem;
      p{
        flex: 1;
        color: #666;
      }
      span{
        display: inline-block;
        width: 10rem;
        text-align: right;
        padding-right: 1rem;
      }
    }
    .time-box{
      display: flex;
      margin: 2rem 0;
      padding-bottom: 2rem;
      overflow-x: scroll;
      .item{
        flex: 1;
        text-align: center;
        i{
          color: #01B86B;
        }
        p{
          line-height: 2;
          color: #666;
          width: 3rem;
          height: 3rem;
          line-height: 3rem;
          border-radius: 50%;
          margin: auto;
          font-size: 1.4rem;
        }
        .active{
          background-color: #01B86B;
          color: #fff;
        }
      }
    }
  }
  .data-info{
    padding-bottom: 2rem;
    display: flex;
    .money,.bonus,.members{
      flex: 1;
      text-align: center;
      b{
        display: block;
        color: #01B86B;
        font-size: 2rem;
        margin-bottom: 0.5rem;
      }
      span{
        color: #999;
        font-size: 1.2rem;
      }
    }
  }
  .support{
    padding: 1rem 0;
    .item{
      display: flex;
      margin-bottom: 0.5rem;
      .supporter{
        flex: 1;
        font-size: 1.4rem;
        img{
          width: 3rem;
          height: 3rem;
          border-radius: 50%;
          vertical-align: middle;
        }
      }
      .money{
        width: 10rem;
        text-align: right;
        line-height: 3rem;
        color: #01B86B;
        font-weight: bold;
      }
    }
  }
  .action{
    margin-top: 2rem;
    text-align: center;
    button{
      width: 80%;
      height: 4rem;
      border: none;
      border-radius: 3px;
      background-color: #01B86B;
      color: #fff;
      font-size: 1.6rem;
    }
    .before{
      cursor: not-allowed;
      background-color: #C0C0C0;
    }
    .stop{
      background-color: #151515;
    }
    .runing{
      background-color:#FFD412;
    }
    .linkto{
      color: #4A90E2;
      text-align: center;
      padding: 3rem 0 1.5rem 0;
      font-size: 1.4rem;
    }
  }
  .instraction{
    padding: 1rem 0;
    border-top: 5px solid #ececec;
    border-bottom: 2px solid #ececec;
    span{
      color: #999;
      font-size: 1.2rem;
      display: block;
      margin-bottom: 1rem;
    }
    p{
      font-size: 1.4rem;
      line-height: 1.4;
    }
  }
  .rank{
    padding: 1rem 0;
    .title{
      font-size: 1.2rem;
      color: #999;
      padding-bottom: 1rem;
    }
    .item{
      margin-top: 1rem;
      padding-bottom: 1rem;
      display: flex;
      .user{
        width: 12rem;
        font-size: 1.4rem;
        line-height: 1.4;
        img{
          width: 4rem;
          height: 4rem;
          border-radius: 50%;
          margin-right: 0.5rem;
          float: left;
          vertical-align: middle;
        }
        .name{
          padding-top: 0.5rem;
        }
        .ranking{
          color: #999;
          font-size: 1.2rem;
        }
      }
      .progress{
        flex: 1;
        .icon{
          padding-top: 0.5rem;
          padding-left: 50%;
          img{
            width: 1.5rem;
            height: 1.5rem;
            border-radius: 50%;
          }
        }
        .box{
          background-color: #F5F5F5;
          border-radius: 0.8rem;
          height: 0.8rem;
          line-height: 1rem;
          color: #fff;
          font-size: 1.2rem;
          overflow: hidden;
          .current{
            height: 0.8rem;
            border-radius: 0.8rem;
            padding-left: 1rem;
            background-color:  #FFD412;
          }
        }
      }
    }
    .nomore{
      text-align: center;
      font-size: 1rem;
      padding-top: 2rem;
      color: #999;
    }
    .nodata{
      text-align: center;
      padding-top: 2rem;
      font-size: 1.4rem;
      color: #999;
    }
  }
}
</style>
